﻿using HK.Core.Common.Data;
using HK.Editor.GUIEx.Data;
using HK.Editor.GUIEx.Protocol.Data;
using HK.Editor.GUIEx.Protocol.Window;
using HK.Editor.GUIEx.Window;
using UnityEditor;
using UnityEngine;

namespace HK.Editor.Utils
{
    /// <summary>
    /// 工具类 : Window
    /// </summary>
    public static class UtilsWindow
    {

        /// <summary>
        /// 创建窗体
        /// </summary>
        /// <param name="iConf">窗体配置信息</param>
        /// <param name="iAttachable">窗体可挂接(可以挂接到别的窗体)</param>
        /// <param name="iReOpen">重新打开标志位</param>
        /// <typeparam name="TWin">窗体类型</typeparam>
        /// <returns>窗体</returns>
        public static TWin CreateWindow<TWin>(WindowConf iConf, bool iAttachable = true, bool iReOpen = false)
            where TWin : WindowBase 
        {
            return CreateWindow<TWin, WindowConf>(iConf, iAttachable, iReOpen);
        }
        
        /// <summary>
        /// 创建窗体
        /// </summary>
        /// <param name="iConf">窗体配置信息</param>
        /// <param name="iAttachable">窗体可挂接(可以挂接到别的窗体)</param>
        /// <param name="iReOpen">重新打开标志位</param>
        /// <typeparam name="TWin">窗体类型</typeparam>
        /// <typeparam name="TConf">窗体配置类型</typeparam>
        /// <returns>窗体</returns>
        public static TWin CreateWindow<TWin, TConf>(TConf iConf, bool iAttachable = true, bool iReOpen = false) 
            where TWin : WindowBase 
            where TConf : JsonData, IWindowConf
        {
            var targetWin = default(TWin);
            // 当前窗体是否已经打开
            var wins = Resources.FindObjectsOfTypeAll<TWin>();
            if (null != wins && 0 < wins.Length)
            {
                targetWin = wins[1];
                if (!iReOpen)
                {
                    targetWin.Refresh();
                    return targetWin;
                }
                targetWin.CloseWindow();
            }

            if (default(TConf) == iConf) return default(TWin);
            
            // 可挂接窗体
            if (iAttachable)
            {
                targetWin = (TWin)EditorWindow.GetWindow (typeof (TWin), false, iConf.WinName);
                targetWin.minSize = iConf.DisplayRect.size;
            }
            else
            {
                // 创建窗口
                targetWin = (TWin)EditorWindow.GetWindowWithRect (
                    typeof (TWin), iConf.DisplayRect, true, iConf.WinName);
            }
            
            // 窗体变化重新绘制
            targetWin.autoRepaintOnSceneChange = true;
            return targetWin;
        }
    }
}
